
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .box {
      width: 450px;
      height: 450px;
      border: 1px solid #aaa;
      position: relative;
      top: 200px;
      left: 200px;
    }

    .small {
      width: 450px;
      height: 450px;
      position: absolute;
    }

    .mask {
      position: absolute;
      background-color: rgba(255, 255, 0, .3);
      width: 225px;
      height: 225px;
      top: 0;
      left: 0;
      display: none;
    }

    .big {
      width: 450px;
      height: 450px;
      border: 1px solid #aaa;
      position: absolute;
      left: 500px;
      top: 0;
      overflow: hidden;
      display: none;
    }

    .big>img {
      width: 900px;
      height: 900px;
      position: absolute;
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="small">
      <img src="./images/s.jpg" alt="">
      <div class="mask"></div>
    </div>
    <div class="big">
      <img src="./images/big.jpg" alt="">
    </div>
  </div>
</body>
<script>
/*
  放大镜：
    效果1和效果2

1.获取元素(box,遮罩，放大用的盒子)

2.给box注册鼠标移入和移出事件

3.控制遮罩和放大盒子显示和隐藏

效果3
1.获取元素(small)

2.注册鼠标的移动事件(mousemove)

3.根据鼠标的位置计算出遮罩应该在位置，设置给遮罩

4.根据鼠标的位置计算出大图应该在的位置，设置给大图


*/
var box=document.querySelector('.box');
var small=document.querySelector('.small');
var mask=document.querySelector('.mask');
var big=document.querySelector('.big');
var bigimg=document.querySelector('.big>img');
// 鼠标移入的时候显示
box.onmouseover=function(){
  mask.style.display='block';
  big.style.display='block';
}
box.onmouseout=function(){
  mask.style.display='none';
  big.style.display='none';
}
small.onmousemove=function(e){
  var mx=e.pageX;
  var my=e.pageY;
  // 遮罩的位置
  var x=mx-box.offsetLeft-mask.offsetWidth/2;
  var y=my-box.offsetTop-mask.offsetHeight/2;
  // 当移动小于0的时候
  x=x<0?0:x;
  y=y<0?0:y;
  // 当移动到右边超出的时候
  var daX=small.offsetWidth-mask.offsetWidth;
  var daY=small.offsetHeight-mask.offsetHeight;
  x=x>daX?daX:x;
  y=y>daY?daY:y;
  mask.style.left=x+'px';
  mask.style.top=y+'px';
  // 放大图片的效果距离

  var imgmaxX=bigimg.offsetWidth-big.clientWidth;
  var imgmaxY=bigimg.offsetHeight-big.clientHeight;
  // 放大图片当前的位置
  var imgX=x*imgmaxX/daX;
  var imgY=y*imgmaxY/daY;
  bigimg.style.left=-imgX+'px';
  bigimg.style.top=-imgY+'px';
}

</script>

</html>